﻿using MediatR;
using RBAC.Domain.WarehouseManagement;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.WarehouseManagement;

namespace RBAC.Write.Api.Application.Handler.ERP.WarehouseManagement
{
    public class DeleteWarehouseListCommandHandler : IRequestHandler<DeleteWarehouseListCommands, APIResult<int>>
    {
        private readonly IBaseRepository<WarehouseList> warehouseListRep;

        public DeleteWarehouseListCommandHandler(IBaseRepository<WarehouseList> warehouseListRep)
        {
            this.warehouseListRep = warehouseListRep;
        }

        public async Task<APIResult<int>> Handle(DeleteWarehouseListCommands request, CancellationToken cancellationToken)
        {
            try
            {
                // 参数验证
                if (request.WarehouseListId <= 0)
                {
                    return new APIResult<int>
                    {
                        Code = APIEnums.Fail,
                        Msg = "仓库ID不能为空",
                        Data = 0
                    };
                }

                // 检查仓库是否存在
                var existingWarehouse = warehouseListRep.GetModel(request.WarehouseListId);
                if (existingWarehouse == null)
                {
                    return new APIResult<int>
                    {
                        Code = APIEnums.Fail,
                        Msg = "仓库不存在，无法删除",
                        Data = 0
                    };
                }

                // 检查仓库是否已被删除
                if (existingWarehouse.IsDeleted)
                {
                    return new APIResult<int>
                    {
                        Code = APIEnums.Fail,
                        Msg = "仓库已被删除",
                        Data = 0
                    };
                }

                // 执行逻辑删除（设置IsDeleted为true）
                existingWarehouse.IsDeleted = true;
                var result = warehouseListRep.Update(existingWarehouse);

                if (result > 0)
                {
                    return new APIResult<int>
                    {
                        Code = APIEnums.Success,
                        Msg = "仓库删除成功",
                        Data = result
                    };
                }
                else
                {
                    return new APIResult<int>
                    {
                        Code = APIEnums.Fail,
                        Msg = "仓库删除失败",
                        Data = 0
                    };
                }
            }
            catch (Exception ex)
            {
                return new APIResult<int>
                {
                    Code = APIEnums.Fail,
                    Msg = "删除仓库时发生错误：" + ex.Message,
                    Data = 0
                };
            }
        }
    }
}
